package implementation.sort.QuickSort;


import anaydis.sort.SorterType;
import com.sun.istack.internal.NotNull;

import java.util.Comparator;
import java.util.List;

public class QuickSortThreeWayPartition extends QuickSorter {

    public QuickSortThreeWayPartition() {
        super(SorterType.QUICK_THREE_PARTITION);
    }

    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
        sort(tComparator, ts, 0, ts.size() - 1);
    }


    private <T> void sort(Comparator<T> comparator, List<T> list, int start, int end) {
        int i = start - 1;
        int j = end;
        int p = start - 1;
        int q = end;
        int k;
        if (end <= start) {
            return;
        }
        for (; ;) {
            while (greater(comparator, list, end, ++i)) ;
            while (greater(comparator, list, --j, end)){
                if (j == start) break;
            }
            if (i >= j){
                break;
            }
            swap(list, i, j);
            if (this.equals(comparator, list, i, end)) {
                p++;
                swap(list, p, i);
            }
            if (equals(comparator, list, end, j)) {
                q--;
                swap(list, q, j);
            }
        }
        swap(list, i, end);
        j = i - 1;
        i = i + 1;
        for (k = start; k <= p; k++, j--) {
            swap(list, k, j);
        }
        for (k = end - 1; k >= q; k--, i++) {
            swap(list, k, i);
        }
        sort(comparator, list, start, j);
        sort(comparator, list, i, end);
    }
}

